#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
#include "SDL.h"
#include "SDL_image.h"
#include "SDL_ttf.h"
#include "sdlmap.h"
#include "sdlevent.h"
#include "sdltext.h"
#include "sdltimer.h"
#include "item.h"
#include "mapitem.h"
#include <vector>
#include "location.h"
#include "tree.h"
#include "itemfactory.h"
#include "mapitemfactory.h"
#include "character.h"
#include "gamemenu.h"
#include "game.h"
using namespace std;

Game::Game(SDL_Surface *screen)
{
       screen_ = screen;
       loca = new Location();
       MapItemFactory *factory = new MapItemFactory();

       for(int a = 0; a < 17; a++)
       {
	      for(int b = 0; b < 44; b++)
	      {
		     loca->map_[a][b] = factory->build("maptile");
	      }
       }

       map_ = new SDLMap(loca, screen_);
       character_ = new Character("Gert-Ingvar", "BlackRanger", 0,0);
       gmenu_ = new GameMenu(character_);
}

Game::~Game()
{
       delete map_;
       //delete tree_;
       delete fps;
}

void Game::run()
{
       // Main game loop
       stringstream is;
       string olle;
       int frames = 0;
       int timer;
       SDLTimer fps2;
       
       SDLText *timer_text = new SDLText(255,255,255,20,"CHECKBK0.TTF", "0");
       fps = new SDLTimer();

       bool running = true;
       fps2.start();

       timer = fps2.getTicks() / 1000;

       while(running)
       {
	      fps->start();
	      event_.Poll();

	      // Print FPS in upper left corner.
	      if(timer != fps2.getTicks() / 1000)
	      {
		     is.clear();
		     is << frames;
		     is >> olle;
		     timer_text->set_text(olle);
		     timer = fps2.getTicks() / 1000;
		     frames = 0;
	      }


	      // Quit if user presses the escape key
	      if(event_.GetKey() == "escape")
	      {
		     running = false;
	      }

	      if(event_.mouse_clicked() == true)
	      {	
		     
		     if(!gmenu_->inventoryVisible())
		     {
			    if(map_->walkable(event_.GetMouseX(), event_.GetMouseY()) == true)
			    {		     
				   // Convert the mouseX,Y coordinates to map coordinates
				   int x = event_.GetMouseX();
				   int y = event_.GetMouseY();
				   map_->getTileXY(x, y);

				   // Create a new walkpath to the clicked world coordinates
				   character_->createWalkPath(loca, x, y, map_);
			    }
		     }
		     gmenu_->is_clicked(event_.GetMouseX(), event_.GetMouseY(), map_);
	      }
	      
	      map_->render(screen_);
	      timer_text->render(screen_);
	      character_->walk(loca, map_);
	      character_->render(screen_);
	      gmenu_->render(screen_);
	      SDL_Flip(screen_);

	      frames++;

	      if(fps->getTicks() < 1000 / FRAMES_PER_SECOND)
	      {		  
		     SDL_Delay((1000/FRAMES_PER_SECOND) - fps->getTicks());
	      }
       }
}
